﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NLog;
using NGinnBPM.Lib.Interfaces.Worklist;
using NGinnBPM.MessageBus;
using NGinnBPM.Lib.Operations.ExternalServices;

namespace NGinnBPM.Services.Worklist 
{
    public class RemoteWorklistHandler : IMessageConsumer<CreateWorkItem>, IWorkListService
    {
        public string WorklistUrl { get; set; }
        private IWorkListService _srv;

        protected IWorkListService WorklistService
        {
            get 
            {
                lock (this)
                {
                    if (_srv != null) return _srv;
                    _srv = (IWorkListService) Activator.GetObject(typeof(IWorkListService), WorklistUrl);
                    return _srv;
                }
                
            }
            set { _srv = value; }
        }


        #region IMessageConsumer<CreateWorkItem> Members

        public void Handle(CreateWorkItem message)
        {
            WorklistService.CreateWorkItem(message);
        }

        #endregion

        #region IWorkListService Members

        public string CreateWorkItem(CreateWorkItem wi)
        {
            return WorklistService.CreateWorkItem(wi);
        }

        public void CancelWorkItem(string wiId, string instanceId)
        {
            WorklistService.CancelWorkItem(wiId, instanceId);
        }

        public void WorkItemCompleted(string wiId, string instanceId)
        {
            WorklistService.WorkItemCompleted(wiId, instanceId);
        }

        #endregion

        public override string ToString()
        {
            return string.Format("RemoteWorklistHandler {0}", WorklistUrl);
        }
    }
}
